﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Dapper.IService;
using Dapper.Model;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace DapperCore.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class TestController : ControllerBase
    {
        [HttpGet]
        public List<User> GetUsers()
        {
            List<User> list = new List<User>();
            User user = new User();
            user.UserId = 1;
            user.UserName = "leon";
            list.Add(user);
            return list;
        }


        [HttpGet]
        public User GetUser(string userId)
        {
            User user = new User();
            user.UserId = 1;
            user.UserName = "leon";
            return user;
        }


        [HttpGet]
        public List<Type> Index()
        {
            List<Type> typeList = new List<Type>();
            var foundDlls = Directory.GetFileSystemEntries(System.AppDomain.CurrentDomain.BaseDirectory, "*" + ".dll", SearchOption.AllDirectories);
            var serviceFiles = Directory.GetFiles(System.AppDomain.CurrentDomain.BaseDirectory, "*.IService.dll");
            foreach (var file in serviceFiles)
            {
                var key = Path.GetFileName(file);
                using (var sr = System.IO.File.OpenRead(file))
                {
                    //var myAssembly = AssemblyLoadContext.Default.LoadFromStream(sr);
                    var bytes = new byte[sr.Length];
                    sr.Read(bytes, 0, (int)sr.Length);
                    var myAssembly = Assembly.Load(bytes);
                    //assemblies.Add(myAssembly);
                    var types = myAssembly.ExportedTypes;
                    foreach (var type in types)
                    {
                        TypeInfo t1 = type.GetTypeInfo();
                        TypeInfo t2 = typeof(IDapperService).GetTypeInfo();
                        if (t2.IsAssignableFrom(t1))
                        //if(typeof(IDapperService).GetType().IsAssignableFrom(type.GetType()))
                        {
                            typeList.Add(type);
                        }
                    }
                }
            }
            return typeList;
        }
    }
}